package com.jie.eclipse.pan.popup.wizard;

import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;

import com.jie.eclipse.pan.config.BasePageConfig;
import com.jie.eclipse.pan.generator.PanGenerator;
import com.jie.eclipse.pan.popup.wizardpage.BasePage;
import com.jie.eclipse.pan.popup.wizardpage.FirstPage;
import com.jie.eclipse.pan.popup.wizardpage.CreatePageTemplate2;
import com.jie.eclipse.pan.popup.wizardpage.FinishPage;

public class CreatePageTemplateWizard extends BaseWizard{
	public static final String page_1 = "page_1";
	public static final String page_2 = "page_2";
	
	FirstPage page1 = null;
	CreatePageTemplate2 page2 = null;
	FinishPage finishPage 	  = null;
	
	public CreatePageTemplateWizard() {
		super();
		page1 = new FirstPage();
		page1.setBaseWizard(this);
		this.addPage(page1);
		
		finishPage = new FinishPage();
		finishPage.setBaseWizard(this);
		this.addPage(finishPage);
		
		this.setWindowTitle("创建页面模板向导");
		this.setHelpAvailable(true);
	}
	
	@Override
	public boolean canFinish() {
		BasePage curPage = (BasePage)this.getContainer().getCurrentPage();
		return curPage == finishPage;
	}
	
	@Override
	public IWizardPage getNextPage(IWizardPage page) {
		BasePage curPage = (BasePage)page;
		BasePage nextPage = curPage.getNxtPage();
		
		if(nextPage == null){
			nextPage = this.finishPage;
		}
		nextPage.setPrePage(curPage);
		
		return nextPage ;
	}
	
	/* (non-Javadoc)
	 * @see org.eclipse.jface.wizard.Wizard#getPreviousPage(org.eclipse.jface.wizard.IWizardPage)
	 */
	@Override
	public IWizardPage getPreviousPage(IWizardPage page) {
		BasePage curPage = (BasePage)page;
		return curPage.getPrePage();
	}
	
	@Override
	public boolean performFinish() {
		((BasePage)this.getContainer().getCurrentPage()).reloadPageConfig();//点击完成的时候需要再次加载页面配置
		
		IRunnableWithProgress op = new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) throws InvocationTargetException {
                try {
                	BasePageConfig pageConfig = getPageConfig();
                	String pageName = pageConfig.getPageName();
                	if(!"".equals(pageName)){
                		IFolder folder = getCurrFolder();
	                	PanGenerator panGen = getPanGenerator();
	                	
                		if(pageConfig.getTpType().toLowerCase().startsWith("base")){
                			//基本模板
		                	//1.UI JSP
                			final IFile ui = folder.getFile(pageName+".jsp");
		                	ui.create(panGen.GeneratorUIJspCode(pageConfig), false, monitor);
		                	
		                	//2.backEnd Jsp
		                	IFile backEnd = folder.getFile(pageName+"_backend.jsp");
		                	backEnd.create(panGen.GeneratorBackEndJspCode(pageConfig), false, monitor);
		                	
		                	//3.config Xml
//		                	final IFile config = folder.getFile(pageName+".pll");
//		                	config.create(panGen.GeneratorConfigXmlCode(pageConfig), false, monitor);
		                	
		                	getShell().getDisplay().asyncExec(new Runnable() {
		            			public void run() {
		            				IWorkbenchPage page = PlatformUI.getWorkbench()
		            						.getActiveWorkbenchWindow().getActivePage();
		            				try {
		            					IDE.openEditor(page, ui, true);
		            				} catch (PartInitException e) {
		            				}
		            			}
		            		});
		                	
                		}else if(pageConfig.getTpType().toLowerCase().equals(BasePageConfig.TAG_TPTYPE_ADVANCED_GRID1)){//成品模板
                			monitor.beginTask("Creating.... ",2);
                			
                			//1.表格crud页面
		                	final IFile ui = folder.getFile(pageName+".jsp");
		                	ui.create(panGen.GeneratorInputStreamByTp(pageConfig.getDataRecord(),"grid/grid1/crud_grid.resource"), false, monitor);
		                	
		                	IFile backend = folder.getFile(pageName+"_backend.jsp");
		                	backend.create(panGen.GeneratorInputStreamByTp(pageConfig.getDataRecord(),"grid/grid1/crud_grid_backend.resource"), false, monitor);
		                	
		                	monitor.worked(1);
		            		monitor.setTaskName("Opening file for editing...");
		                	getShell().getDisplay().asyncExec(new Runnable() {
		            			public void run() {
		            				IWorkbenchPage page = PlatformUI.getWorkbench()
		            						.getActiveWorkbenchWindow().getActivePage();
		            				try {
		            					IDE.openEditor(page, ui, true);
		            					//IDE.openEditor(page, left, true);
		            				} catch (PartInitException e) {
		            				}
		            			}
		            		});
                		}else if(pageConfig.getTpType().toLowerCase().equals(BasePageConfig.TAG_TPTYPE_ADVANCED_GRID2)){//成品模板
                			monitor.beginTask("Creating.... ",2);
                			
                			//左查右编
                			String leftPageName = pageName+"_left.jsp";
                			String rightPageName = pageName+"_right.jsp";
                			
                			pageConfig.getDataRecord().spsv("lefturl", leftPageName);
                			pageConfig.getDataRecord().spsv("righturl", rightPageName);
                			
                			//1.主页面
                			final IFile ui = folder.getFile(pageName+".jsp");
		                	ui.create(panGen.GeneratorCrud1Code(pageConfig,"main"), false, monitor);
		                	
		                	//2.左页面
		                	final IFile left = folder.getFile(leftPageName);
		                	left.create(panGen.GeneratorCrud1Code(pageConfig,"left"), false, monitor);
		                	
		                	IFile left_backend = folder.getFile(pageName+"_left_backend.jsp");
		                	left_backend.create(panGen.GeneratorCrud1Code(pageConfig,"leftbackend"), false, monitor);
		                	
		                	//3.右页面
		                	final IFile right = folder.getFile(rightPageName);
		                	right.create(panGen.GeneratorCrud1Code(pageConfig,"right"), false, monitor);
		                	
		                	IFile right_backend = folder.getFile(pageName+"_right_backend.jsp");
		                	right_backend.create(panGen.GeneratorCrud1Code(pageConfig,"rightbackend"), false, monitor);
		                	
		                	monitor.worked(1);
		            		monitor.setTaskName("Opening file for editing...");
		                	getShell().getDisplay().asyncExec(new Runnable() {
		            			public void run() {
		            				IWorkbenchPage page = PlatformUI.getWorkbench()
		            						.getActiveWorkbenchWindow().getActivePage();
		            				try {
		            					IDE.openEditor(page, ui, true);
		            					//IDE.openEditor(page, left, true);
		            				} catch (PartInitException e) {
		            				}
		            			}
		            		});
                		}
	                	
                		
                	}
                } catch (Exception e) {
                    throw new InvocationTargetException(e);
                } finally {
                    monitor.done();
                }
            }
        };
        
        try {
            getContainer().run(true, false, op);
        } catch (InterruptedException e) {
            return false;
        } catch (InvocationTargetException e) {
        	e.printStackTrace();
            Throwable realException = e.getTargetException();
            MessageDialog.openError(getShell(), "Error", realException.getMessage());
            return false;
        }
		return true;
	}
	
}
